package com.xiaodou.mjf.application.core.manager;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.transaction.Transactional;

import org.springframework.stereotype.Component;

import com.google.common.collect.Lists;
import com.xiaodou.mjf.application.basic.utils.OperatorUtils;
import com.xiaodou.mjf.application.basic.utils.SequenceGenerator;
import com.xiaodou.mjf.application.core.service.AuditLogService;
import com.xiaodou.mjf.application.core.service.FinancingAttributeService;
import com.xiaodou.mjf.application.core.service.FinancingLoanService;
import com.xiaodou.mjf.application.core.service.FinancingService;
import com.xiaodou.mjf.application.core.service.FinancingStatisticsService;
import com.xiaodou.mjf.application.core.service.FullscaleAuditLogService;
import com.xiaodou.mjf.application.core.service.LoanService;
import com.xiaodou.mjf.application.core.service.MeiliAuditLogService;
import com.xiaodou.mjf.application.core.service.SequenceService;
import com.xiaodou.mjf.application.core.service.XiaodouAuditLogService;
import com.xiaodou.mjf.entity.basic.Operator;
import com.xiaodou.mjf.entity.core.AuditLog;
import com.xiaodou.mjf.entity.core.Financing;
import com.xiaodou.mjf.entity.core.FinancingAttribute;
import com.xiaodou.mjf.entity.core.FinancingLoan;
import com.xiaodou.mjf.entity.core.FinancingStatistics;
import com.xiaodou.mjf.entity.core.FullscaleAuditLog;
import com.xiaodou.mjf.entity.core.Loan;
import com.xiaodou.mjf.entity.core.MeiliAuditLog;
import com.xiaodou.mjf.entity.core.XiaodouAuditLog;
import com.xiaodou.mjf.infrastructure.common.app.CommonManager;
import com.xiaodou.mjf.infrastructure.common.components.Result;
import com.xiaodou.mjf.infrastructure.common.utils.DateUtils;
import com.xiaodou.mjf.infrastructure.common.utils.StringUtils;

@Component
@Transactional
public class FinancingManager extends CommonManager {

	@Resource
	SequenceService sequenceService;
	@Resource
	FinancingService financingService;
	@Resource
	FinancingStatisticsService financingStatisticsService;
	@Resource
	FinancingLoanService financingLoanService;
	@Resource
	LoanService loanService;
	@Resource
	AuditLogService auditLogService;
	@Resource
	XiaodouAuditLogService xiaodouAuditLogService;
	@Resource
	MeiliAuditLogService meiliAuditLogService;
	@Resource
	FinancingAttributeService financingAttributeService;
	@Resource
	FullscaleAuditLogService fullscaleAuditLogService;

	/**
	 * 小豆产品保存
	 * 
	 * @param financing
	 * @return
	 */
	public Result xiaodouSave(Financing financing) throws Exception {
		Result result = new Result();
		try {

			List<FinancingLoan> loans = Lists.newArrayList();

			Double loanAmount = 0.00D;
			if (financing.getLoanIds().length() > 0) {
				String[] loanIds = financing.getLoanIds().split(",");
				for (String loanId : loanIds) {
					Loan loan = loanService.get(loanId);
					loanAmount += loan.getLoanAmount();
					FinancingLoan financingLoan = new FinancingLoan();
					financingLoan.setLoanId(loanId);
					loan.setFlag(Loan.FLAG_USE);
					loans.add(financingLoan);
					loanService.save(loan);
				}
			}

			String codeNo = SequenceGenerator.generateProdCodeNo(SequenceGenerator.TYPE_FINANCING);
			financing.setCode(codeNo);
			financing.setAmount(loanAmount);
			financing.setType(Financing.TYPE_XIAODOU);
			financing.setStatus(Financing.WAIT_AUDIT);
			financingService.save(financing);
			//

			FinancingStatistics statistics = financingStatisticsService.findByfinanceId(financing.getId());

			if (statistics == null) {
				statistics = new FinancingStatistics();
				statistics.setId(financing.getId());
				statistics.setFinanceId(financing.getId());
			}
			statistics.setTotalAmount(loanAmount);
			statistics.setResidualAmount(loanAmount);

			financingStatisticsService.save(statistics);

			// delete financeId delete all financingLoan record
			financingLoanService.deleteByFinancingId(financing.getId());

			for (FinancingLoan loan : loans) {
				loan.setFinancingId(financing.getId());
			}
			financingLoanService.save(loans);

		} catch (Exception ex) {
			result.setSuccess(false);
			result.setMessage("保存失败:" + ex.toString());
			logger.error(ex.toString());
			throw ex;
		}
		result.setSuccess(true);
		return result;
	}

	/**
	 * 分期申请审核
	 * 
	 * @param loan
	 * @return
	 * @throws Exception
	 */
	public boolean auditCommit(String id, Integer audtiStatus, String content) throws Exception {
		boolean flag = false;
		try {
			Loan loan = loanService.get(id);
			Operator operator = OperatorUtils.getOperator();
			if (loan != null) {
				// 更新状态
				loan.setStatus(audtiStatus);
				loanService.save(loan);
				// 插入audit_log表
				AuditLog auditLog = new AuditLog();
				auditLog.setOperatorId(operator.getId());
				auditLog.setLoanId(loan.getId());
				auditLog.setDescription(content);
				auditLog.setStatus(audtiStatus);
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				Date date = sdf.parse(DateUtils.getDateTime());
				auditLog.setAuditTime(date);
				auditLogService.save(auditLog);
			}
		} catch (Exception ex) {
			flag = false;
			logger.error(ex.toString());
			throw ex;
		}
		flag = true;
		return flag;
	}

	/**
	 * 美丽理财产品审核
	 * 
	 * @param id
	 * @param audtiStatus
	 * @param content
	 * @return
	 * @throws Exception
	 */
	public boolean meiliAuditCommit(String id, Integer audtiStatus, String content) throws Exception {
		boolean flag = false;
		try {
			Financing financing = financingService.get(id);
			Operator operator = OperatorUtils.getOperator();
			if (financing != null) {
				// 更新状态
				financing.setStatus(audtiStatus);
				financing.setInvestStatus(Financing.INVEST_STATUS_SALE);
				financingService.save(financing);
				// 插入meili_audit_log表
				MeiliAuditLog meiliAuditLog = new MeiliAuditLog();
				meiliAuditLog.setOperatorId(operator.getId());
				meiliAuditLog.setMeiliId(financing.getId());
				meiliAuditLog.setDescription(content);
				meiliAuditLog.setStatus(audtiStatus);
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				Date date = sdf.parse(DateUtils.getDateTime());
				meiliAuditLog.setAuditTime(date);
				meiliAuditLogService.save(meiliAuditLog);
			}
		} catch (Exception ex) {
			flag = false;
			logger.error(ex.toString());
			throw ex;
		}
		flag = true;
		return flag;
	}

	/**
	 * 满标审核
	 * @param id
	 * @param audtiStatus
	 * @param content
	 * @return
	 * @throws Exception
	 */
	public boolean fullscaleAuditCommit(String id, Integer audtiStatus, String content) throws Exception {
		boolean flag = false;
		try {
			Financing financing = financingService.get(id);

			Operator operator = OperatorUtils.getOperator();
			if (financing != null) {
				// 更新状态
				if (audtiStatus == 0) {
					financing.setInvestStatus(Financing.INVEST_STATUS_FOR_LOAN);
					financingService.save(financing);
					List<FinancingLoan> financingLoanList = financingLoanService.findByFinancingId(financing.getId());
					if (StringUtils.notEmpty(financingLoanList)) {
						for (FinancingLoan financingLoan : financingLoanList) {
							financingLoan.setInvestStatus(Financing.INVEST_STATUS_FOR_LOAN);
							financingLoanService.save(financingLoan);
							//更新loan表finance_status=5[放款中]
							Loan loan = loanService.get(financingLoan.getLoanId());
							loan.setFinanceStatus(Loan.LOAN_STATUS_FOR_LOAN);
							loanService.save(loan);
						}
					}
				}
				// 插入fullscale_audit_log表
				FullscaleAuditLog fullscaleAuditLog = new FullscaleAuditLog();
				fullscaleAuditLog.setOperatorId(operator.getId());
				fullscaleAuditLog.setFullscaleId(financing.getId());
				fullscaleAuditLog.setDescription(content);
				fullscaleAuditLog.setStatus(audtiStatus);
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				Date date = sdf.parse(DateUtils.getDateTime());
				fullscaleAuditLog.setAuditTime(date);
				fullscaleAuditLogService.save(fullscaleAuditLog);
				
			}
		} catch (Exception ex) {
			flag = false;
			logger.error(ex.toString());
			throw ex;
		}
		flag = true;
		return flag;
	}

	/**
	 * 小豆理财产品审核
	 * 
	 * @param id
	 * @param audtiStatus
	 * @param content
	 * @return
	 * @throws Exception
	 */
	public boolean xiaodouAuditCommit(String id, Integer audtiStatus, String content) throws Exception {
		boolean flag = false;
		try {
			Financing financing = financingService.get(id);
			Operator operator = OperatorUtils.getOperator();
			if (financing != null) {
				// 更新状态
				financing.setStatus(audtiStatus);
				financing.setInvestStatus(Financing.INVEST_STATUS_SALE);
				financingService.save(financing);
				// 插入xiaodou_audit_log表
				XiaodouAuditLog xiaodouAuditLog = new XiaodouAuditLog();
				xiaodouAuditLog.setOperatorId(operator.getId());
				xiaodouAuditLog.setXiaodouId(financing.getId());
				xiaodouAuditLog.setDescription(content);
				xiaodouAuditLog.setStatus(audtiStatus);
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				Date date = sdf.parse(DateUtils.getDateTime());
				xiaodouAuditLog.setAuditTime(date);
				xiaodouAuditLogService.save(xiaodouAuditLog);
			}
		} catch (Exception ex) {
			flag = false;
			logger.error(ex.toString());
			throw ex;
		}
		flag = true;
		return flag;
	}

	/**
	 * 美丽产品保存
	 * 
	 * @param financing
	 * @return
	 * @throws Exception
	 */
	public Result meiliSave(Financing financing) throws Exception {
		Result result = new Result();
		try {
			financing.setType(Financing.TYPE_MEILI);
			financing.setStatus(Financing.WAIT_AUDIT);
			String codeNo = SequenceGenerator.generateProdCodeNo(SequenceGenerator.TYPE_FINANCING);
			financing.setCode(codeNo);

			financingService.save(financing);

			FinancingAttribute attribute = financingAttributeService.get(financing.getId());
			FinancingStatistics statistics = financingStatisticsService.get(financing.getId());

			if (attribute == null) {
				attribute = new FinancingAttribute();
				attribute.setId(financing.getId());
			}
			attribute.setRefundAmount(Double.parseDouble(financing.getRefundAmount()));
			attribute.setUseGuide(financing.getUseGuide());
			attribute.setTimeLimit(financing.getTimeLimit());
			attribute.setPromise(financing.getPromise());
			attribute.setAgreementTitle(financing.getAgreementTitle());
			attribute.setAgreementUrl(financing.getAgreementUrl());

			//
			if (statistics == null) {
				statistics = new FinancingStatistics();
				statistics.setId(financing.getId());
			}
			statistics.setFinanceId(financing.getId());
			statistics.setCount(0);
			statistics.setResidualCount(financing.getCount());
			statistics.setTotalAmount(financing.getAmount());
			statistics.setResidualAmount(financing.getAmount());

			financingStatisticsService.save(statistics);
			financingAttributeService.save(attribute);

		} catch (Exception ex) {
			result.setSuccess(false);
			result.setMessage("保存失败:" + ex.toString());
			logger.error(ex.toString());
			throw ex;
		}
		result.setSuccess(true);
		return result;
	}

	/**
	 * 小豆删除
	 * 
	 * @param financing
	 * @return
	 * @throws Exception
	 */
	public Result meiliDelete(Financing financing) throws Exception {
		Result result = new Result();
		try {
			List<Loan> loans = Lists.newArrayList();

			if (financing != null) {
				financing.setStatus(Financing.DELETE);
				if (financing.getLoanIds() != null && financing.getLoanIds().length() > 0) {
					String[] loanIds = financing.getLoanIds().split(",");
					for (String loanId : loanIds) {
						Loan loan = loanService.get(loanId);
						loan.setFlag(Loan.FLAG_NOTUSE);
						loans.add(loan);
					}
					financingService.save(financing);
					loanService.save(loans);
				}
			} else {
				result.setSuccess(false);
				result.setMessage("数据不存在");
				return result;
			}

		} catch (Exception ex) {
			result.setSuccess(false);
			result.setMessage("保存失败:" + ex.toString());
			logger.error(ex.toString());
			throw ex;
		}
		result.setSuccess(true);
		return result;
	}

}
